/*
 * @Author: zhengzhuang
 * @Date: 2020-11-04 10:38:03
 * @LastEditors: zhengzhuang
 * @LastEditTime: 2020-12-07 13:42:03
 * @Description: In User Settings Edit
 * @FilePath: /C20Driver/lib/widget/webview_widget.dart
 */
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:C20Driver/utils/utils.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:C20Driver/resources/app_storage_interface.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/utils/locate_info.dart';
import 'package:C20Driver/widget/app_share.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

///定义GlobalKey
class WebviewWidget extends StatefulWidget {
  String url;
  WebviewWidget({this.url, Key key}) : super(key: key);
  @override
  WebviewWidgetState createState() => WebviewWidgetState();
}

class WebviewWidgetState extends State<WebviewWidget> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();
  WebViewController _webController;
  String _url;
  bool _loadingState = false;
  String _token;
  DriverInformation provider;
  @override
  void initState() {
    super.initState();
    provider = Provider.of<DriverInformation>(context, listen: false);
    print("orderID ${provider.driverInfo.userId}");
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
    _getToken();
  }

  void _getToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _token = prefs.getString(AppStorageInterface.LOGINTOKEN);
  }

  void reloadWebView(String dataUrl) async {
    _url = dataUrl;
    setState(() {
      _loadingState = true;
    });
    _webController?.loadUrl(dataUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Stack(
      children: [
        WebView(
          // initialUrl:provider.driverInfo.userId=="1628112731137645854"?"http://h5.tt.huashichuxing.com/zeroDownPayment": widget.url, 租车服务测试
          initialUrl: widget.url,
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) async {
            print("onWebViewCreated---------------1");
            _webController = webViewController;
            _webController.clearCache();
          },
          javascriptChannels: <JavascriptChannel>[
            _toasterJavascriptChannel(context),
            _getAppToken(context),
            _getCurrentLatlng(context),
            _getLocationInfo(context),
            _jumpRouter(context),
            _wxShare(context),
            _appPayment(context),
            _openAmap(context),
            _openBaiduMap(context),
            _openPhotos(context),
            _jumpWebViewRouter(context),
            _pushInfo(context)
          ].toSet(),
          navigationDelegate: (NavigationRequest request) async {
            if (Platform.isAndroid) {
              if (request.url.contains("wx.tenpay.com")) {
                _webController
                    .loadUrl(request.url, headers: {"referer": widget.url});
                return NavigationDecision.prevent;
              }
            }

            if (Platform.isIOS) {
              if (request.url.startsWith('alipay://') ||
                  request.url.startsWith('weixin://wap/pay?')) {
                await launch(request.url);
                return NavigationDecision.prevent;
              } else {
                return NavigationDecision.navigate;
              }
            } else {
              if (request.url.startsWith('alipays://') ||
                  request.url.startsWith('weixin://wap/pay?')) {
                await launch(request.url);
                return NavigationDecision.prevent;
              } else {
                return NavigationDecision.navigate;
              }
            }
          },
          onPageStarted: (String url) async {
            print("onPageStarted---------------1");
            print("webview设置token11111");
          },
          onPageFinished: (String url) async {
            // print("onPageFinished---------------2222222" + url);
            // if (mounted) {
            //   setState(() {
            //
            //   });
            // }
            _loadingState = true;
            /// webview设置token
            // SharedPreferences prefs = await SharedPreferences.getInstance();
            // _webController
            //     .evaluateJavascript(
            //     "(function() { try { window.localStorage.setItem('token', '${prefs.getString(AppStorageInterface.LOGINTOKEN)}');return window.localStorage.authToken; } catch (err) { return err; } })();")
            //     .then((result) {});
          },
          gestureNavigationEnabled: true,
        ),
      ],
    ));
  }

  @override
  void dispose() {
    super.dispose();
  }
// 传递信息
  JavascriptChannel _pushInfo(BuildContext context) {
    return JavascriptChannel(
        name: 'pushInfo',
        onMessageReceived: (JavascriptMessage message) {
          ToastX.center(message.message);
          var mobile=18561784507;
          _webController.evaluateJavascript('pushInfoToJs("$mobile")') .then((value) => print("eeeeeeee"+value));
        });
  }
  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }

  /// 获取当前token
  /// js调用：getCurrentLatlng.postMessage('传递的数据');
  JavascriptChannel _getAppToken(BuildContext context) {
    return JavascriptChannel(
        name: 'getAppToken',
        onMessageReceived: (JavascriptMessage message) async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          String _token =
              prefs.getString(AppStorageInterface.LOGINTOKEN); // 存储token到本地
          _webController.evaluateJavascript('getAppToken("$_token")');
        });
  }

  /// 获取当前经纬度
  /// js调用：getCurrentLatlng.postMessage('传递的数据');
  JavascriptChannel _getCurrentLatlng(BuildContext context) {
    return JavascriptChannel(
        name: 'getCurrentLatlng',
        onMessageReceived: (JavascriptMessage message) async {
          Location _dataInfo = await LocateInfo.getLocation(context);
          List latLng = [_dataInfo.latLng.latitude, _dataInfo.latLng.longitude];
          _webController
              .evaluateJavascript('getCurrentLatlng("${latLng.toString()}")');
        });
  }

  /// 通过经纬度查询当前位置
  JavascriptChannel _getLocationInfo(BuildContext context) {
    return JavascriptChannel(
        name: 'getLocationInfo',
        onMessageReceived: (JavascriptMessage message) async {
          LatLng _locationInfo = LatLng.fromJson(jsonDecode(message.message));
          LocateInfo().getLocationInfo(_locationInfo).then((value) =>
              _webController.evaluateJavascript('getLocationInfo("$value")'));
        });
  }

  /// 路由跳转
  JavascriptChannel _jumpRouter(BuildContext context) {
    return JavascriptChannel(
        name: 'jumpRouter',
        onMessageReceived: (JavascriptMessage message) async {
          NavigatorUtil.jump(context, message.message);
        });
  }

  /// 微信分享
  JavascriptChannel _wxShare(BuildContext context) {
    return JavascriptChannel(
        name: 'wxShare',
        onMessageReceived: (JavascriptMessage message) async {
          // AppShare().webviewWxMiniprogramShare(context, "0040", message.message);
        });
  }

  /// App支付
  JavascriptChannel _appPayment(BuildContext context) {
    return JavascriptChannel(
        name: 'appPayment',
        onMessageReceived: (JavascriptMessage message) {
          // AppPaymentWidget.webviewShow(context, _webController, message.message);
        });
  }

  /// webview路由跳转
  JavascriptChannel _jumpWebViewRouter(BuildContext context) {
    return JavascriptChannel(
        name: 'jumpWebViewRouter',
        onMessageReceived: (JavascriptMessage message) async {
          NavigatorUtil.jumpWebView(context, message.message).then((value) {
            _webController?.evaluateJavascript(
                "(function() { try { window.localStorage.setItem('token', '$_token');return window.localStorage.authToken; } catch (err) { return err; } })();");
          });
        });
  }



  /// 打开高德地图导航
  JavascriptChannel _openAmap(BuildContext context) {
    return JavascriptChannel(
        name: 'openAmap',
        onMessageReceived: (JavascriptMessage message) {
          // LatLngLocation _locationInfo = LatLngLocation.fromJson(jsonDecode(message.message));
          // MapUtil.gotoAMap(_locationInfo.longitude, _locationInfo.latitude);
        });
  }

  /// 打开百度地图导航
  JavascriptChannel _openBaiduMap(BuildContext context) {
    return JavascriptChannel(
        name: 'openBaiduMap',
        onMessageReceived: (JavascriptMessage message) {
          // LatLngLocation _locationInfo = LatLngLocation.fromJson(jsonDecode(message.message));
          // MapUtil.gotoBaiduMap(_locationInfo.longitude, _locationInfo.latitude);
        });
  }
  /// 打开相册
  JavascriptChannel _openPhotos(BuildContext context) {
    return JavascriptChannel(
        name: 'openPhotoses',
        onMessageReceived: (JavascriptMessage message) {
          print("ffffffffffffffffffffff  ${message.message}");
          Utils.imageUpload(context).then((value) {
            _webController.evaluateJavascript('flutterCallJsMethod("$value")') .then((value) => print("发送成功"));;
          });

          // LatLngLocation _locationInfo = LatLngLocation.fromJson(jsonDecode(message.message));
          // MapUtil.gotoBaiduMap(_locationInfo.longitude, _locationInfo.latitude);
        });
  }

  Widget favoriteButton() {
    return FutureBuilder<WebViewController>(
        future: _controller.future,
        builder: (BuildContext context,
            AsyncSnapshot<WebViewController> controller) {
          if (controller.hasData) {
            return FloatingActionButton(
              onPressed: () async {
                final String url = await controller.data.currentUrl();
                Scaffold.of(context).showSnackBar(
                  SnackBar(content: Text('Favorited $url')),
                );
              },
              child: const Icon(Icons.favorite),
            );
          }
          return Container();
        });
  }
}
